<template>
    <div class="container">
        <!-- 微信图标 -->
        <div class="text-line">使用微信扫一扫登录</div>
        <div class="text-line">「AI_CHAT」</div>
        <img :src="qrcodeUrl" alt="微信二维码">

    </div>
</template>

<script setup>

import { ref, onMounted } from "vue";
import { wechatQrCode } from '@/api/user';
import { wechatTryLogin } from '@/api/user';
import { useTokenStore } from '@/stores/user';
import { useRouter } from 'vue-router'

const router = useRouter();

const qrcodeUrl = ref('');
const openid = ref('');


const store = useTokenStore();

onMounted(async () => {
    try {
        const result = await wechatQrCode();
        console.log('wechat result:' + result);
        console.log('wechat resultData:' + result.data.qrcode);
        console.log('wechat resultData:' + result.data.sseEmitterId);

        qrcodeUrl.value = result.data.qrcode;


        let eventSource = new EventSource("http://localhost:9090/user/createSse/" + result.data.sseEmitterId);
        eventSource.onopen = function () {

            console.log("create sse success!");
        }
        eventSource.onmessage = async function (e) {
            console.log('wechat data:' + e.data);
            const wechatUser = JSON.parse(e.data);
            console.log('wechatUser:' + wechatUser.headimgurl);
            store.wechat_nickname = wechatUser.nickname;
            store.openid = wechatUser.openid;
            store.headimgurl = wechatUser.headimgurl;
            console.log("store.headimgurl:" + store.headimgurl);

            eventSource.close();
            

            try{
                const openid = store.openid;
                console.log("send openid to trywechatlogin:"+ openid);
                const result = await wechatTryLogin(openid);
                store.login(result.data);
                router.push("/ai_chat");


            }catch(error){
                console.log("wechatTryLogin failed:" + error);
            }
            


        }
        eventSource.onerror = function () {
            console.log("SSE链接失败");
        }

    } catch (error) {
        console.log('wechat error:' + error);
    }

})


</script>

<style scoped>
.container {
    display: flex;
    flex-direction: column;
    /* 使子元素垂直排列 */
    align-items: center;
    /* 垂直居中子元素 */
    height: 95vh;
    /* 容器高度设置为视口高度的95% */
    text-align: center;
    /* 确保文本也水平居中 */
}

.text-line {
    margin-bottom: 10px;
    /* 在文本行之间添加间隔 */
}
</style>